import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-15
 * Time: 23:29
 */
//1. 通过query string传递
// 如果在url中使用中文需要用转码（urlencode）
@WebServlet("/getParameter")
public class GetParameter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //前端通过url的query string传递username和password两个属性
        String username = req.getParameter("username");
        if (username == null) {
            System.out.println("username这个key在query string中不存在");
        }
        String password = req.getParameter("password");
        if (username == null) {
            System.out.println("password这个key在query string中不存在");
        }
        System.out.println("username=" + username + ",password=" + password);
        resp.getWriter().write("ok");
    }


    //2. form表单
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //给请求设置编码，告诉服务器应该使用何种方式解码
        req.setCharacterEncoding("utf8");
        //前端通过body，以form表单的形式，把username和password传给服务器
        String username = req.getParameter("username");
        if (username == null) {
            System.out.println("username这个key在body中不存在");
        }
        String password = req.getParameter("password");
        if (username == null) {
            System.out.println("password这个key在body中不存在");
        }
        System.out.println("username=" + username + ",password=" + password);
        resp.getWriter().write("ok");
    }
}
